package com.um.jdy.platform.market.manager;

import com.um.jdy.common.market.entity.dto.ActivityDTO;
import com.um.jdy.common.market.entity.po.Activity;
import com.um.jdy.common.market.entity.po.ActivityGoods;
import com.um.jdy.common.market.entity.po.ActivityGoodsOption;
import com.um.jdy.common.market.entity.po.SeckillTimes;
import com.um.jdy.common.market.entity.vo.ActivityVO;
import com.um.jdy.common.market.service.ActivityGoodsOptionService;
import com.um.jdy.common.market.service.ActivityGoodsService;
import com.um.jdy.common.market.service.ActivityService;
import com.um.jdy.common.market.service.SeckillTimesService;
import com.um.jdy.common.shop.entity.po.Goods;
import com.um.jdy.common.shop.service.GoodsService;
import com.um.jdy.platform.market.entity.dto.ActivityPageDTO;
import com.um.jdy.platform.market.entity.dto.SaveGroupDTO;
import com.um.jdy.platform.market.entity.dto.SaveSeckillDTO;
import com.um.jdy.platform.market.entity.vo.*;
import com.um.jdy.platform.shop.entity.vo.GoodsPageVO;
import com.um.springboot.starter.config.SystemSQL;
import com.um.springboot.starter.dao.BaseDao;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.manager.BasePlusManager;
import com.um.springboot.starter.orm.params.ListDTO;
import com.um.springboot.starter.utils.DateUtil;
import com.um.springboot.starter.utils.JSONUtil;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 管理类：平台活动表
 */
@Component
@Transactional
public class ActivityManager extends BasePlusManager<ActivityService, Activity, ActivityDTO, ActivityVO, ActivityPageDTO, ListDTO> {

    @Autowired
    BaseDao dao;

    @Autowired
    SeckillTimesService seckillTimesService;

    @Autowired
    ActivityGoodsService activityGoodsService;

    @Autowired
    ActivityGoodsOptionService activityGoodsOptionService;

    @Autowired
    GoodsService goodsService;

    public Page<ActivityVO> getActivityPage(ActivityPageDTO pageDTO) {

        Page<ActivityVO> page = new Page<>();
        page.setPageNo(pageDTO.getPageNo());
        page.setPageSize(pageDTO.getPageSize());

        String type = StringUtil.getTrim(pageDTO.getType(), "%");
        String title = StringUtil.getTrim(pageDTO.getTitle(), "%");
        String status = StringUtil.getTrim(pageDTO.getStatus());

        String sql = SystemSQL.getInstance().getSystemSQL("get_activity_page");
        String sumSql = SystemSQL.getInstance().getSystemSQL("get_activity_count");

        String condition = "title like '" + title + "'" + " and type like '" + type + "'";

        if (status.equals("0")) {//未开始
            condition += " and begin_date > NOW()";
        }
        if (status.equals("1")) {//进行中
            condition += " and begin_date <= NOW() and end_date >= NOW()";
        }
        if (status.equals("2")) {//已结束
            condition += " and end_date < NOW() ";
        }

        sql = sql.replace("[condition]", condition);
        sumSql = sumSql.replace("[condition]", condition);

        page = service.getViewModelPageBySql(page, sql, sumSql, ActivityVO.class, new Object[]{getComId()});

        List<ActivityVO> result = page.getResult();

        Date todayDate = new Date();

        for (ActivityVO activityVO : result) {
            Date beginDate = activityVO.getBeginDate();
            Date endDate = activityVO.getEndDate();
            if (DateUtil.daysBetween(todayDate, beginDate) > 0) {//未开始
                activityVO.setStatus("0");
            }
            if (DateUtil.daysBetween(beginDate, todayDate) >= 0 && DateUtil.daysBetween(endDate, todayDate) <= 0) {//进行中
                activityVO.setStatus("1");
            }
            if (DateUtil.daysBetween(todayDate, endDate) < 0) {//已结束
                activityVO.setStatus("2");
            }
        }

        return page;

    }

    public SeckillResultVO getActivitySeckillGoods(ActivityDTO activityDTO) {

        String activityId = StringUtil.getTrim(activityDTO.getMarketActivityId());

        Activity activity = service.getEntity(activityId);

        SeckillResultVO result = new SeckillResultVO();

        List<SeckillTimesGoodsVO> timesList = seckillTimesService.getViewModelList("get_seckill_times_list", SeckillTimesGoodsVO.class, new String[]{activityId,getComId()});

        for (SeckillTimesGoodsVO times : timesList) {

            List<ActivityGoodsResultVO> goodsList = service.getViewModelList("get_activity_goods_list_by_times_id", ActivityGoodsResultVO.class,
                    new String[]{times.getMarketSeckillTimesId(),getComId()});

            for (ActivityGoodsResultVO goods : goodsList) {

                if (goods.getThumb() == null || goods.getThumb().equals("")) {
                    goods.setThumbList(new ArrayList<>());
                } else {
                    goods.setThumbList(JSONUtil.parseJSONToList(StringUtil.getTrim(goods.getThumb())));
                }

                List<GoodsOptionItemVO> optionList = service.getViewModelList("get_activity_goods_option_list", GoodsOptionItemVO.class,
                        new String[]{goods.getMarketActivityGoodsId(),getComId()});
                goods.setOptionList(optionList);

            }

            times.setGoodsList(goodsList);

        }

        if (timesList.size() <= 0) {
            timesList = new ArrayList<>();
            SeckillTimesGoodsVO item = new SeckillTimesGoodsVO();
            item.setStartTime("00:00");
            item.setEndTime("01:00");
            item.setGoodsList(new ArrayList<>());
            timesList.add(item);
        }

        result.setList(timesList);
        result.setActivity(activity == null ? new ActivityVO() : UMBeanUtils.copyBean(activity, ActivityVO.class));

        return result;

    }

    public boolean saveSeckill(SaveSeckillDTO seckillDTO) {

        ActivityDTO activityDTO = seckillDTO.getActivity();
        List<SeckillTimesGoodsVO> spikeList = seckillDTO.getSpikeItems();

        String beginDate = DateUtil.getDateString(activityDTO.getBeginDate(), "yyyy-MM-dd");
        String endDate = DateUtil.getDateString(activityDTO.getEndDate(), "yyyy-MM-dd");
        String type = StringUtil.getTrim(activityDTO.getType());
        String activityId = StringUtil.getTrim(activityDTO.getMarketActivityId());

        //限时秒杀需要判断活动时间是否有重复
        long count = service.getCountBySqlName("get_activity_is_exist_count", new String[]{activityId,getComId(), type, beginDate, endDate, beginDate, endDate});
        if (count > 0) {
            throw new ServiceException("该时间段已存在相同活动！");
        }

        if (activityId.isEmpty()) {
            activityDTO.setCreateTime(new Date());
        }

        Activity activity = UMBeanUtils.copyBean(activityDTO, Activity.class);
        service.save(activity);

        activityId = StringUtil.getTrim(activity.getMarketActivityId());

        activityGoodsService.deleteTrue("market_activity_id", activityId);

        //获取原有的场次
        List<SeckillTimes> oldSpikeList = seckillTimesService.getList("market_activity_id", activityId);

        //处理新的场次
        Map dataSpike = new Hashtable();
        for (SeckillTimesGoodsVO spike : spikeList) {
            String key = StringUtil.getTrim(spike.getMarketSeckillTimesId());
            if (!key.isEmpty()) {
                dataSpike.put(key, spike);
            }
        }

        for (SeckillTimes times : oldSpikeList) {
            String oldKey = StringUtil.getTrim(times.getMarketSeckillTimesId());
            if (!dataSpike.containsKey(oldKey)) {//删除原有场次
                seckillTimesService.deleteTrue("market_seckill_times_id", oldKey);
            }
        }

        int sortNo = 1;
        for (SeckillTimesGoodsVO spike : spikeList) {
            SeckillTimes item = new SeckillTimes();
            if (!StringUtil.getTrim(spike.getMarketSeckillTimesId()).isEmpty()) {
                item.setMarketSeckillTimesId(StringUtil.getTrim(spike.getMarketSeckillTimesId()));
            }
            item.setMarketActivityId(activityId);
            item.setSortNo(sortNo++);
            item.setStartTime(spike.getStartTime());
            item.setEndTime(spike.getEndTime());

            seckillTimesService.save(item);

            //保存秒杀场次商品
            List<ActivityGoodsResultVO> goodsList = spike.getGoodsList();
            for (ActivityGoodsResultVO goods : goodsList) {

                if (this.validateGoodsInActivity(StringUtil.getTrim(goods.getShopGoodsId()), activityId)) {
                    Goods entity = goodsService.getEntity(StringUtil.getTrim(goods.getShopGoodsId()));
                    throw new ServiceException("保存失败，" + StringUtil.getTrim(entity.getShopGoodsName()) + "已参加活动！");
                }

                ActivityGoods activityGoods = new ActivityGoods();
                activityGoods.setMarketActivityId(activityId);
                activityGoods.setShopGoodsId(goods.getShopGoodsId());
                activityGoods.setActivityPrice(goods.getActivityPrice());
                activityGoods.setMarketSeckillTimesId(item.getMarketSeckillTimesId());
                activityGoods.setCreateTime(new Date());
                activityGoodsService.save(activityGoods);

                //保存秒杀场次商品规格
                List<GoodsOptionItemVO> optionList = goods.getOptionList();
                for (GoodsOptionItemVO optionItemVO : optionList) {
                    ActivityGoodsOption activityOption = new ActivityGoodsOption();
                    activityOption.setMarketActivityGoodsId(activityGoods.getMarketActivityGoodsId());
                    activityOption.setShopGoodsOptionId(StringUtil.getTrim(optionItemVO.getShopGoodsOptionId()));
                    activityOption.setActivityPrice(optionItemVO.getActivityPrice());
                    activityOption.setActivityStock(optionItemVO.getActivityStock());
                    activityOption.setOriginalTitle(optionItemVO.getTitle());
                    activityOption.setOriginalPrice(optionItemVO.getPrice());

                    activityGoodsOptionService.save(activityOption);
                }

            }

        }

        return true;

    }

    public boolean validateGoodsInActivity(String goodsId, String activityId) {
        Map activityExist = dao.queryMapBySQLName("get_activity_goods_detail", new Object[]{goodsId,getComId()});
        if (null != activityExist && !StringUtil.equals(activityId, activityExist.get("market_activity_id"))) {
            return true;
        }
        activityExist = dao.queryMapBySQLName("get_full_reduce_goods_detail", new Object[]{goodsId,getComId()});
        return null != activityExist && !StringUtil.equals(activityId, activityExist.get("market_activity_id"));
    }

    public boolean saveGroup(SaveGroupDTO saveGroupDTO) {

        ActivityDTO activityDTO = saveGroupDTO.getActivity();

        List<ActivityGoodsResultVO> goodsList = saveGroupDTO.getGoodsList();

        Activity activity = UMBeanUtils.copyBean(activityDTO, Activity.class);
        if (StringUtil.isEmpty(activity.getMarketActivityId())) {
            activity.setCreateTime(new Date());
        }
        service.save(activity);

        String marketActivityId = StringUtil.getTrim(activity.getMarketActivityId());

        //删除已报名商品
        activityGoodsService.delete("market_activity_id", marketActivityId);
        activityGoodsOptionService.delete("market_activity_id", marketActivityId);

        for (ActivityGoodsResultVO goods : goodsList) {
            if (this.validateGoodsInActivity(StringUtil.getTrim(goods.getShopGoodsId()), marketActivityId)) {
                Goods entity = goodsService.getEntity(StringUtil.getTrim(goods.getShopGoodsId()));
                throw new ServiceException("保存失败，" + StringUtil.getTrim(entity.getShopGoodsName()) + "已参加活动！");
            }

            ActivityGoods activityGoods = new ActivityGoods();
            activityGoods.setMarketActivityId(marketActivityId);
            activityGoods.setShopGoodsId(goods.getShopGoodsId());
            activityGoods.setActivityPrice(goods.getActivityPrice());
            activityGoods.setCreateTime(new Date());

            activityGoodsService.save(activityGoods);

            List<GoodsOptionItemVO> optionList = goods.getOptionList();
            if(optionList == null){
                throw new ServiceException("请设置商品规格价格！");
            }
            for (GoodsOptionItemVO optionItemVO : optionList) {
                ActivityGoodsOption activityOption = new ActivityGoodsOption();
                activityOption.setMarketActivityGoodsId(activityGoods.getMarketActivityGoodsId());
                activityOption.setShopGoodsOptionId(StringUtil.getTrim(optionItemVO.getShopGoodsOptionId()));
                activityOption.setOriginalTitle(optionItemVO.getTitle());
                activityOption.setActivityPrice(optionItemVO.getActivityPrice());
                activityOption.setActivityStock(optionItemVO.getActivityStock());
                activityOption.setGroupNum(optionItemVO.getGroupNum());
                activityOption.setMarketActivityId(marketActivityId);

                activityGoodsOptionService.save(activityOption);
            }

        }

        return true;

    }

    public GroupResultVO getActivityGoods(ActivityDTO activityDTO) {
        String marketActivityId = StringUtil.getTrim(activityDTO.getMarketActivityId());

        if (marketActivityId.isEmpty()) {
            return new GroupResultVO();
        }

        GroupResultVO result = new GroupResultVO();

        Activity activity = service.getEntity(marketActivityId);

        List<ActivityGoodsResultVO> goodsList = service.getViewModelList("get_activity_goods_list", ActivityGoodsResultVO.class, new String[]{marketActivityId,getComId()});

        for (ActivityGoodsResultVO goods : goodsList) {

            if (goods.getThumb() == null || goods.getThumb().equals("")) {
                goods.setThumbList(new ArrayList<>());
            } else {
                goods.setThumbList(JSONUtil.parseJSONToList(StringUtil.getTrim(goods.getThumb())));
            }

            List<GoodsOptionItemVO> optionList = service.getViewModelList("get_activity_goods_option_list", GoodsOptionItemVO.class,
                    new String[]{goods.getMarketActivityGoodsId(),getComId()});
            goods.setOptionList(optionList);

        }

        result.setList(goodsList);
        result.setActivity(activity == null ? new ActivityVO() : UMBeanUtils.copyBean(activity, ActivityVO.class));

        return result;

    }

}
